package com.lanxigua.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class Http implements Runnable {
	private static Http INSTANCE = null;
	private static final String API_URL = "http://192.168.1.5/server.aspx";
	private JSONObject response = null;
	static private HttpClient httpClient = null;
	private static List<NameValuePair> Params = null;
	private static Map<String, Object> params = new HashMap<String, Object>();
	public static Handler handler = null;
	private static boolean isString = false;
	private static boolean isOjbect = true;
	private static boolean isArray = false;	
	
	public Http() {
		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);

			if (httpClient == null) {
				httpClient = new DefaultHttpClient();
			}
		} catch (Exception e) {
			
		} finally {
			
		}
	}

	public static Http connect(Action Action) {
		if (INSTANCE == null) {
			INSTANCE = new Http();
		}
		Http.Params = new ArrayList<NameValuePair>();
		Http.Params.add(new BasicNameValuePair("api_key",
				"8b11c921-25c4-4d05-9cf2-120c72487544"));
		Http.Params.add(new BasicNameValuePair("action",
				com.lanxigua.utils.Common.getActionName(Action)));
		return INSTANCE;
	}

	public Http handler(Handler handler) {
		Http.handler = handler;
		return this;
	}

	public static Http location(Double latitude, Double longitude) {
		return INSTANCE;
	}
	
	public Http post(Map<String, Object> Params) throws ErrorException {
		Http.params = Params;
		return this;
	}

	public Http post() throws ErrorException {
		return this.post(null);
	}

	public Http response(JsonObject JsonObject) throws Exception {
		Http.isString = false;
		Http.isOjbect = true;
		Http.isArray = false;
		return this;
	}
	
	public Http response(JsonArray JsonArray) throws Exception {
		Http.isString  = false;
		Http.isOjbect = false;
		Http.isArray = true;
		return this;
	}
	
	public Http response(JsonString JsonString){
		Http.isString = true;
		Http.isOjbect = false;
		Http.isArray = false;
		return this;
	}

	public void start() {
		new Thread(this).start();
	}

	public void run() {
		HttpPost httppost = new HttpPost(API_URL);
		try {
			if (Http.params != null) {
				for (Map.Entry<String, Object> entry : Http.params.entrySet()) {
					Http.Params.add(new BasicNameValuePair(entry.getKey(),
							new String(((String) entry.getValue().toString()))));
				}
			}
			
			httppost.setEntity(new UrlEncodedFormEntity(Http.Params));

			HttpResponse response = httpClient.execute(httppost);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			StringBuilder builder = new StringBuilder();

			String str = "";
			while ((str = reader.readLine()) != null) {
				builder.append(str);
			}
			reader.close();

			this.response = new JSONObject(builder.toString());

			if (this.response != null) {
				Message message;
				Object object = null;
				if (this.response.getBoolean("success")) {
					if (Http.isOjbect){
						object = this.response.getJSONObject("content");
					}else if (Http.isArray){
						object = this.response.getJSONArray("content");
					}else if (Http.isString){
						object = this.response.getString("content");
					}
					message = Http.handler.obtainMessage(0, object);
				} else {
					message = Http.handler.obtainMessage(-1,
							this.response.getString("message"));
				}
				Http.handler.sendMessage(message);
			}
		} catch (Exception e) {
			Log.e("HTTP", "HTTP:" + e.getMessage());
		}
	}
}